package cn.dqy.gotanserver.support;

//用来记录客户端的响应，将其写入指定文件

import cn.dqy.gotanserver.code.CodeUtils;
import cn.dqy.gotanserver.config.ConfigClass;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.*;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Optional;

@Component
public class ClientRespondRecordUtils {
    static Logger logger = LoggerFactory.getLogger(ClientRespondRecordUtils.class);

    @Autowired
    ConfigClass configClass;

    public void create(){
        String path = configClass.getFileRootPath() + "GoTanLog.txt";
        File file=new File(path);
        if(!file.exists()){
            logger.info("文件不存在，创建文件");
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
                logger.error("创建文件失败 "+e);
            }
        }else {
            logger.info("{} 已存在，无需创建");
        }
    }

    public void wInfo(String s,boolean append,boolean isAddDownload){
        String path = configClass.getFileRootPath() + "GoTanLog.txt";
        File file=new File(path);
        try {
            if(isAddDownload){
                String format = String.format("<a href='/download?fp=%s'>下载</a>", s.substring(5,s.length()));
                s=s+ format;
            }
            FileUtils.writeStringToFile(file,s + "\r\n", CodeUtils.globalCharSet,append);
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("写入GoTanLog失败 "+e);
        }
    }

    public String readGoTanLog(){
        String path = configClass.getFileRootPath() + "GoTanLog.txt";
        File file=new File(path);
        try {
            List<String> strings = FileUtils.readLines(file, CodeUtils.globalCharSet);
            StringBuilder sb=new StringBuilder();
            for(String item : strings){
                sb.append(  item + "<br/>");
            }

            return sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("读取GoTanLog失败 "+e);
        }
        return "";
    }
}
